#include "settime.hpp"
#include <FS.h>
#include <SPIFFS.h>

int Hour = 0, Min = 0, Sec = 0;
#include <WiFiUdp.h>

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com", 60 * 60 * 8, 30 * 60 * 1000);

void connectWifi()
{
    int scanWifiNum = WiFi.scanNetworks();
    for (int i = 0; i < scanWifiNum; i++) //扫描Wifi，并对比Wifi信息库中是否存在对应Wifi信息
    {

        for (int j = 0; j < wifidata.size(); j++) //对比Wifi信息库中是否存在对应Wifi信息
        {
            if (WiFi.SSID(i) == wifidata[j].ssid) //存在该wifi信息
            {
                Serial.print("try connect to ssid:");
                Serial.println(wifidata[j].ssid);

                WiFi.begin(wifidata[j].ssid.c_str(), wifidata[j].pswd.c_str()); //尝试链接该wifi
                int count = 0;
                while (WiFi.status() != WL_CONNECTED)
                {
                    delay(100);
                    Serial.print(".");
                    count++;
                    if (count > 100)
                    {
                        Serial.println();
                        break; //链接超时
                    }
                }
                break;
            }
        }
        if (WiFi.status() == WL_CONNECTED)
        {
            Serial.println("");
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());

            timeClient.begin();
            if(updataTime()==true)
            {
              break;
            }
            else
            {
              Serial.println("wifi可能无法连接到网络");
              WiFi.disconnect();
              while(WiFi.status()==WL_CONNECTED);
              //断开Wifi
            }
        }
    }
    displaySetShowNum(Hour * 100 + Min);
}

void timeUpdataInitCallback()
{
    Sec++;
    if (Sec >= 60)
    {
        Sec = 0;
        Min++;
        if (WiFi.status() == WL_CONNECTED)
        {
            //Serial.println("updata time");
            updataTime();
        }
        if (Min >= 60)
        {
            Min = 0;
            Hour++;
            if (Hour >= 24)
            {
                Hour = 0;
            }
        }
    }
    displaySetShowNum(Hour * 100 + Min);
}

Ticker timeUpdata;
void timeUpdataInit()
{

    timeUpdata.attach_ms(1000, timeUpdataInitCallback);
}

void setTimeInit()
{
    timeUpdataInit();
    connectWifi();
}
bool updataTime()
{
    if(timeClient.update()==false)
    {
      return 0;
    }
    Hour = timeClient.getHours();
    Min = timeClient.getMinutes();
    Sec = timeClient.getSeconds(); //每一个小时更新一次时间

    displaySetShowNum(Hour * 100 + Min);
    return true;
}
